<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <div slot="header">
                <el-button type="primary" size="default" icon="el-icon-plus" @click="addTrademark"
                    v-visit="'btn.Trademark.add'">添加</el-button>

            </div>
            <el-table :data="trademarkList.records" border stripe style="margin-bottom: 10px;" v-loading="loading">
                <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
                <el-table-column label="品牌名称" prop="tmName"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template slot-scope="scope">
                        <img :src="scope.row.logoUrl" alt="" width="100" height="80">
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="{row,$index}">
                        <el-button type="warning" size="small" icon="el-icon-edit-outline" title="修改品牌"
                            @click="toEdit(row)">
                        </el-button>

                        <el-popconfirm :title="`您确定删除${row.tmName}吗？`" @confirm="remove(row)"
                            style="margin-left: 10px;">
                            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete-solid"
                            title="删除品牌"></el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="getTrademarkList"
                :current-page.sync="pageCurrent" :page-sizes="[1, 3, 5, 10]" :page-size="pageSize"
                layout="prev, pager, next, jumper,->,total, sizes" :total="trademarkList.total" background
                :pager-count="7">
            </el-pagination>

            <!-- 对话框 -->

            <el-dialog :title="tmObj.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
                <el-form :model="tmObj" :rules="rules" ref="tmObjRef" label-width="100px" style="width: 80%;">
                    <el-form-item label="品牌名称" prop="tmName">
                        <el-input v-model="tmObj.tmName"></el-input>
                    </el-form-item>
                    <el-form-item label="品牌LOGO" prop="logoUrl">
                        <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="tmObj.logoUrl" :src="tmObj.logoUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="save">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>

    </div>
</template>

<script>

import { mapState } from 'vuex';
import { reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/trademark'
import { remove } from 'js-cookie';
export default {
    data() {

        return {
            pageCurrent: 1,
            pageSize: 3,
            loading: false,
            dialogFormVisible: false,
            tmObj: {
                logoUrl: '',
                tmName: ''
            },
            rules: {
                tmName: [
                    { required: true, message: '请输入名称' },
                    { required: true, trigger: "blur", validator: this.validateTmName },
                ],
                logoUrl: [
                    { required: true, message: "请你上传logo图片" }
                ],
            }
        }
    },
    mounted() {
        // 调方法获取品牌数据
        this.getTrademarkList()
    },
    methods: {
        //自定义校验规则
        validateTmName(rule, value, callback) {
            if (value.length < 2 || value.length > 10) {
                // callback(new Error('长度必须在2-10个之间'))
                callback('长度必须在2-10个之间2')  // 不通过
            } else {
                callback() // 通过
            }
        },
        // 获取品牌数据
        async getTrademarkList(pageCurrent = 1) {
            this.loading = true
            this.pageCurrent = pageCurrent
            let pageSize = this.pageSize
            // 派发一个action
            await this.$store.dispatch('trademark/getTrademarkList', { pageCurrent, pageSize })
            this.loading = false
        },
        // 修改显示几条
        handleSizeChange(pageSize) {
            this.pageSize = pageSize
            this.getTrademarkList()
        },
        // 添加品牌按钮
        addTrademark() {
            this.tmObj = {}
            this.dialogFormVisible = true
            this.$refs.tmObjRef?.resetFields()
        },
        // 修改品牌按钮
        toEdit(row) {
            this.tmObj = row
            this.dialogFormVisible = true
            this.$refs.tmObjRef?.resetFields()
        },
        // 点击确定添加/修改品牌
        save() {
            // 对所有表单项进行统一验证
            this.$refs.tmObjRef.validate(async (valid) => {
                if (valid) {
                    try {
                        await reqAddOrUpdateTrademark(this.tmObj)
                        this.dialogFormVisible = false
                        this.$message({
                            message: this.tmObj.id ? '修改品牌成功' : '添加品牌成功',
                            type: 'success',
                            center: true
                        });
                        // 再次发请求获取列表
                        this.getTrademarkList()
                    } catch (error) {
                        this.$message({
                            message: this.tmObj.id ? '修改品牌失败' : '添加品牌失败',
                            type: 'success',
                            center: true
                        });
                    }
                }
            })

        },
        // 上传
        handleAvatarSuccess(res, file) {
            this.tmObj.logoUrl = res.data
        },
        beforeAvatarUpload(file) {
            // const isJPG = file.type === 'image/jpeg';
            // const isLt2M = file.size / 1024 / 1024 < 2;

            // if (!isJPG) {
            //     this.$message.error('上传头像图片只能是 JPG 格式!');
            // }
            // if (!isLt2M) {
            //     this.$message.error('上传头像图片大小不能超过 2MB!');
            // }
            // return isJPG && isLt2M;
        },

        // 删除品牌
        async remove(row) {
            console.log(this.trademarkList.records.length);
            //    console.log(row);
            try {
                await reqDeleteTrademark(row.id)
                this.$message({
                    message: `删除${row.tmName}成功`,
                    type: 'success',
                    center: true
                });
                // 再次发请求获取列表
                this.getTrademarkList(this.trademarkList.records.length === 1 && this.pageCurrent > 1 ? this.pageCurrent - 1 : this.pageCurrent)
            } catch (error) {

            }
        }


    },
    computed: {
        ...mapState('trademark', {
            trademarkList: state => state.trademarkList
        })
    }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>